package com.xlf.service.base.service.impl;

import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xlf.common.core.constant.Constants;
import com.xlf.common.core.exception.BizException;
import com.xlf.common.core.util.StringUtils;
import com.xlf.pojo.base.Problem;
import com.xlf.pojo.base.ProblemType;
import com.xlf.service.base.mapper.ProblemMapper;
import com.xlf.service.base.service.ProblemTypeService;
import com.xlf.service.base.mapper.ProblemTypeMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
* @author 小新
* @description 针对表【problem_type】的数据库操作Service实现
* @createDate 2023-10-03 10:34:41
*/
@Service
public class ProblemTypeServiceImpl extends ServiceImpl<ProblemTypeMapper, ProblemType>
    implements ProblemTypeService{

    @Resource
    ProblemMapper problemMapper;
    @Override
    public List<ProblemType> getList() {
        LambdaQueryWrapper<ProblemType> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(ProblemType::getId,ProblemType::getName)
                .eq(ProblemType::getStatus, Constants.NORMAL);
        return list(wrapper);
    }

    @Override
    public List<ProblemType> getList(ProblemType problemType) {

        LambdaQueryWrapper<ProblemType> wrapper = new LambdaQueryWrapper<>();
        wrapper.likeRight(StringUtils.isNotEmpty(problemType.getName()),ProblemType::getName,problemType.getName())
                .eq(problemType.getStatus()!=null,ProblemType::getStatus,problemType.getStatus());

        List<ProblemType> list = list(wrapper);
        if(StringUtils.isNotEmpty(list)){
            list.forEach(item -> {
                Long aLong = problemMapper.selectCount(new LambdaQueryWrapper<Problem>()
                        .eq(Problem::getProblemTypeId,item.getId()));
                item.setProblemNum(Math.toIntExact(aLong));
            });
        }
        return list;
    }

    @Override
    public void delete(List<String> ids) {
        Assert.notNull(ids,() -> new BizException("列表不能为空"));
        ids.forEach(item -> {
            Long count = problemMapper.selectCount(new LambdaQueryWrapper<Problem>()
                    .eq(Problem::getProblemTypeId, item));
            if(count > 0){
                throw new BizException("该题库下存在题目，不允许删除！");
            }
            removeById(item);
        });
    }

    @Override
    public boolean updateStatus(ProblemType problemType) {
        return lambdaUpdate().set(ProblemType::getStatus,problemType.getStatus()).eq(ProblemType::getId,problemType.getId()).update();

    }
}




